package com.tarena.demo.luban.gateway.filters;

import com.tarena.demo.luban.gateway.exception.GatewayException;
import com.tarena.demo.luban.gateway.handler.MyErrorHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpCookie;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Slf4j
@Component
public class AuthenticationFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        log.info("请求经过了AuthenticationFilter");
        try {
            checkToken(exchange);
        } catch (GatewayException e) {
            log.error("AuthenticationFilter校验失败，{}",e.getMsg());
            return new MyErrorHandler().handle(exchange, e);
        } catch (Throwable t) {
            log.error("AuthenticationFilter校验失败，{}",t.getMessage());
            return new MyErrorHandler().handle(exchange, t);
        }
        log.info("AuthenticationFilter校验成功，放行");
        return chain.filter(exchange);
        //todo 思考：Authorization,Cookie的形式怎么校验
    }

    @Override
    public int getOrder() {
        return 200;
    }

    /**
     * 校验token
     */
    private void checkToken(ServerWebExchange exchange) throws GatewayException{
        // 获取请求
        ServerHttpRequest request = exchange.getRequest();
        // 获取token值，来源可能是QueryParams,Headers,Cookies
        String token;
        token = request.getQueryParams().getFirst("token");
        // 若token为空，则继续从Headers中获取
        if (token == null){
            token = request.getHeaders().getFirst("Authorization");
        }
        // 若token为空，则继续从Cookies中获取
        if (token == null) {
            HttpCookie tokenCookie = request.getCookies().getFirst("token");
            if (tokenCookie != null)
                token = tokenCookie.getValue();
        }
        // 判断token是否为空，若为空，说明没有携带凭证，抛出异常
        if (token == null)
            throw new GatewayException("token不能为空");
        // token不为空，校验格式
        log.info("获取token:{}", token);
        // 使用正则表达式判断token格式是否符合要求(\\d{10})
        if (!token.matches("\\d{10}"))
            throw new GatewayException("token格式错误");
    }

}
